﻿#include "CAudioBroadcast.h"

#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QDir>
#include <QFileInfo>
#include "glog/logging.h"
#include "CommonType.h"

using namespace zl;

CAudioBroadcast* CAudioBroadcast::Instance_ = nullptr;
CAudioBroadcast::CAudioBroadcast()
	: player_(new QMediaPlayer)
	, play_list_(new QMediaPlaylist)
{
	LOG(WARNING) << "create audio boradcast instance...";
	play_list_->setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
	player_->setAudioRole(QAudio::MusicRole);
	player_->setVolume(50);
    player_->setPlaylist(play_list_);
}

CAudioBroadcast::~CAudioBroadcast()
{
	LOG(WARNING) << "release audio broadcast instance...";

	player_->stop();
	player_->deleteLater();
	play_list_->clear();
	play_list_->deleteLater();
}

CAudioBroadcast * CAudioBroadcast::Instance()
{
	if (Instance_ == nullptr)
	{
		Instance_ = new CAudioBroadcast;
	}

	return Instance_;
}

void CAudioBroadcast::Release()
{
	if (Instance_ == nullptr)
	{
		return;
	}

	Instance_->UnInit();
	delete Instance_;
	Instance_ = nullptr;
}

int32_t CAudioBroadcast::Init()
{
	LOG(INFO) << "audio broadcast init...";
	// todo
	return zl::EResult_Success;
}

int32_t CAudioBroadcast::UnInit()
{
	LOG(INFO) << "audio broadcast uninit...";
	// todo
	return zl::EResult_Success;
}

int32_t CAudioBroadcast::Play(int index)
{
	LOG(INFO) << "audio broadcast play: " << index;
	player_->stop();
	play_list_->setCurrentIndex(index);
	player_->play();

	return zl::EResult_Success;
}

int32_t CAudioBroadcast::Play(const std::string &name)
{
    LOG(INFO) << "audio braodcast play: " << name;
    int cnt = play_list_->mediaCount();
    for (int i = 0; i < cnt; ++i)
    {
        auto mediacontent = play_list_->media(i);
        LOG(INFO) << "name: " << mediacontent.canonicalUrl().toString().toStdString();
        if (mediacontent.canonicalUrl().toString().indexOf(name.c_str()) != -1)
        {
            return Play(i);
        }
    }

    return 0;
}

int32_t CAudioBroadcast::Stop()
{
	LOG(INFO) << "audio broadcast stop";
	player_->stop();
	return zl::EResult_Success;
}

int32_t CAudioBroadcast::LoadMediaResource(const std::string & path)
{
	LOG(INFO) << "audio broadcast load media resource: " << path;
	play_list_->clear();

	QDir dir(path.c_str());
	if (!dir.exists())
	{
		return zl::EResult_Success;
	}

	foreach(const QFileInfo& fi, dir.entryInfoList(QDir::Files, QDir::Name))
	{
//        QRegExp reg("^\\w+.mp3$");
        QRegExp reg("^.+.mp3$");
		if (!reg.exactMatch(fi.fileName()))
		{
			continue;
		}

		LOG(INFO) << "load media content: " << fi.absoluteFilePath().toStdString();
		auto ret = play_list_->addMedia(QUrl::fromLocalFile(fi.absoluteFilePath()));
		if (!ret)
		{
			LOG(ERROR) << "load media content failed";
		}
	}
	return zl::EResult_Success;
}

int32_t CAudioBroadcast::ClearMediaResource()
{
	LOG(INFO) << "audio broadcast clear media resource";
	player_->stop();
	play_list_->clear();
	return zl::EResult_Success;
}
